<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form :rules="rules"
             :model="employee"
             ref="employeeForm"
             label-width="80px"
             label-position="right"
    >
      <el-form-item label="员工号" prop="no">
        <el-input v-model="employee.no" clearable style="width:150px"/>
      </el-form-item>
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="employee.name" clearable style="width:150px"/>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate()">
          <svg-icon icon-class="save"/>
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { employeeApi } from '@/api'

export default {
  data() {
    return {
      // 初始化讲师默认数据
      employee: {
        no: '',
        name: ''
      },
      rules: {
        no: [{ required: true, message: '请输入员工号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }]
      },
      saveBtnDisabled: false // 保存按钮是否禁用,防止表单重复提交
    }
  },
  // 页面渲染时从route中拿出id然后取数据
  created() {
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id)
    }
  },
  methods: {
    // 判断是保存还是更新
    saveOrUpdate() {
      // 禁用保存按钮
      this.saveBtnDisabled = true
      this.$refs.employeeForm.validate((valid) => {
        if (valid) {
          if (!this.employee.id) {
            this.saveData()
          } else {
            this.updateData()
          }
        } else {
          this.$message.warning('请完成必填项')
          this.saveBtnDisabled = false
        }
      })
    },
    // 保存
    saveData() {
      employeeApi.queryByNo(this.employee.no).then(response => {
        if (!response.data) {
          employeeApi.insert(this.employee).then(response => {
            this.$message.success({
              message: response.message
            })
            this.$router.push({ path: '/employee' })
          })
        } else {
          this.$message.warning('工号重复')
          this.saveBtnDisabled = false
        }
      })
    },
    fetchDataById(id) {
      employeeApi.queryById(id).then(response => {
        this.employee = response.data.item
      })
    },
    // 更新
    updateData() {
      employeeApi.update(this.employee).then(response => {
        this.$message.success({
          message: response.message
        })
        this.$router.push({ path: '/employee' })
      })
    }
  }
}
</script>

<style lang="scss">
@import "~@/assets/css/upload_avatar.scss";
</style>
